
const _=require('underscore');
const Socket_io = require('socket.io');

/*****
io.eio.clientsCount  // 链接数量
socket.adapter.rooms // 所有房间
socket.nsp.connected // 所有链接
//私发消息 _.findWhere(io.sockets.sockets,{nickname:'burt'}).emit();
***/

function Socket(server){
    const io = Socket_io.listen(server, {pingTimeout:10000});


    // 检查昵称是否重复
    // io.sockets.sockets 返回所有在线的socket对象集合
    var checkNickname = function(name){
        for(var k in io.sockets.sockets){
            if(io.sockets.sockets.hasOwnProperty(k)){
                if(io.sockets.sockets[k] && io.sockets.sockets[k].nickname == name){
                    return true;
                }
            }
        }
        return false;
    }

    io.on('connection',(socket)=>{
        //用户登录
        socket.on('login', (nickname)=>{
            if(checkNickname(nickname)){  //用户已登录
                socket.emit('userExists');
            }else{
                //socket.id;   唯一
                socket.nickname=nickname;
                socket.emit('loginSuccess');   //登录成功
                //var nums=io.eio.clientsCount;  //在线人数
                //io.sockets.emit('system',username,nums,'login');
            }
        });
    });

};


module.exports = Socket;